package com.vcc.boss.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaCheckSafe;
import com.mybatisflex.core.paginate.Page;
import com.vcc.boss.core.component.OssComponent;
import com.vcc.boss.core.config.OssConfig;
import com.vcc.core.annotations.RepeatSubmit;
import com.vcc.core.annotations.RestPack;
import com.vcc.core.exception.ProgramException;
import com.vcc.data.entity.WhiteLabel;
import com.vcc.service.boss.request.whiteLabel.AuditWhiteLabelDto;
import com.vcc.service.boss.request.whiteLabel.CreateWhiteLabelDto;
import com.vcc.service.boss.request.whiteLabel.UpdateWhiteLabelDto;
import com.vcc.service.boss.response.whiteLabel.WhiteLabelVoBoss;
import com.vcc.service.sa.BossUserUtil;
import com.vcc.service.service.WhiteLabelService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;

@RestController
@RequestMapping("/white-label")
public class WhiteLabelController {


    @Resource
    private WhiteLabelService whiteLabelService;
    @Resource
    private OssComponent ossComponent;
    @Resource
    private OssConfig ossConfig;


    @RestPack
    @SaCheckLogin
    @GetMapping("/get")
    @SaCheckPermission("admin:brandable")
    public WhiteLabelVoBoss get() {
        Long id = BossUserUtil.getId();
        // 根据用户ID查询白标信息
        WhiteLabel whiteLabel;
        try {
            whiteLabel = whiteLabelService.getByBossUserId(id);
        } catch (Exception e) {
            return null;
        }
        WhiteLabelVoBoss whiteLabelVo = new WhiteLabelVoBoss();
        whiteLabelVo.setId(whiteLabel.getId());
        whiteLabelVo.setBossUserId(whiteLabel.getBossUserId());
        whiteLabelVo.setDomain(whiteLabel.getDomain());
        whiteLabelVo.setAdminDomain(whiteLabel.getAdminDomain());
        whiteLabelVo.setName(whiteLabel.getName());
        whiteLabelVo.setLogo(whiteLabel.getLogo());
        if (StringUtils.isNotBlank(whiteLabel.getLogo())) {
            whiteLabelVo.setLogoUrl(ossComponent.generateTokenUrl(whiteLabel.getLogo(), ossConfig.getStaticBucketName()).toString());
        }
        whiteLabelVo.setHomeLogo(whiteLabel.getHomeLogo());
        if (StringUtils.isNotBlank(whiteLabel.getHomeLogo())) {
            whiteLabelVo.setHomeLogoUrl(ossComponent.generateTokenUrl(whiteLabel.getHomeLogo(), ossConfig.getStaticBucketName()).toString());
        }
        whiteLabelVo.setLoginLeftImage(whiteLabel.getLoginLeftImage());
        if (StringUtils.isNotBlank(whiteLabel.getLoginLeftImage())) {
            whiteLabelVo.setLoginLeftImageUrl(ossComponent.generateTokenUrl(whiteLabel.getLoginLeftImage(), ossConfig.getStaticBucketName()).toString());
        }
        whiteLabelVo.setStatus(whiteLabel.getStatus());
        whiteLabelVo.setRemark(whiteLabel.getRemark());
        // 返回白标信息
        return whiteLabelVo;
    }


    @RestPack
    @SaCheckLogin
    @GetMapping("/paging")
    @SaCheckPermission("admin:brandable:list:view")
    public Page<WhiteLabelVoBoss> paging(Integer pageNumber, Integer pageSize, Long bossUserId, String domain, String name, Integer status) {

        Page<WhiteLabelVoBoss> page = whiteLabelService.pageing(name, domain, bossUserId, status, pageNumber, pageSize);
        return page.map(whiteLabelVo -> {
            // 检查OSS配置
            if (ossConfig == null || ossConfig.getStaticBucketName() == null) {
                throw new ProgramException("OSS配置错误");
            }
            // 生成带token的URL
            if (StringUtils.isNotBlank(whiteLabelVo.getLogo())) {
                whiteLabelVo.setLogoUrl(ossComponent.generateTokenUrl(whiteLabelVo.getLogo(), ossConfig.getStaticBucketName()).toString());
            }
            if (StringUtils.isNotBlank(whiteLabelVo.getHomeLogo())) {
                whiteLabelVo.setHomeLogoUrl(ossComponent.generateTokenUrl(whiteLabelVo.getHomeLogo(), ossConfig.getStaticBucketName()).toString());
            }
            if (StringUtils.isNotBlank(whiteLabelVo.getLoginLeftImage())){
                whiteLabelVo.setLoginLeftImageUrl(ossComponent.generateTokenUrl(whiteLabelVo.getLoginLeftImage(), ossConfig.getStaticBucketName()).toString());
            }
            return whiteLabelVo;
        });
    }


    @RestPack
    @PostMapping("upload")
    @SaCheckLogin
    @SaCheckPermission("admin:brandable")
    public HashMap<String, String> upload(@RequestBody MultipartFile file, @RequestParam(value = "domain", required = true) String domain, @RequestParam(value = "ossType", required = true) String ossType) {
        // 检查OSS配置
        if (ossConfig == null || ossConfig.getStaticBucketName() == null) {
            throw new ProgramException("OSS配置错误");
        }
        // 检查文件是否为空
        if (file == null || file.isEmpty()) {
            throw new ProgramException("上传的文件不能为空");
        }
        if (StringUtils.isBlank(domain)) {
            throw new ProgramException("域名不能为空");
        }
        if (StringUtils.isBlank(ossType)) {
            throw new ProgramException("OSS类型不能为空");
        }
        String filename = domain + "_" + ossType + "." + StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
        ossComponent.uploadFile(file, filename, ossConfig.getStaticBucketName());
        HashMap<String, String> map = new HashMap<>();
        map.put("name", filename);
        map.put("url", ossComponent.generateTokenUrl(filename, ossConfig.getStaticBucketName()).toString());
        return map;
    }


    @RestPack
    @PostMapping("create")
    @SaCheckLogin
    @RepeatSubmit
    @SaCheckPermission("admin:brandable")
    public void create(@RequestBody @Validated CreateWhiteLabelDto createWhiteLabelDto) {
        // 创建白标信息
        WhiteLabel whiteLabel;
        if (whiteLabelService.existsByBossUserId(BossUserUtil.getId())) {
            whiteLabel = whiteLabelService.getByBossUserId(BossUserUtil.getId());
            if (whiteLabel.getStatus() == 2) {
                throw new ProgramException("当前白标信息正在审核中，无法重复提交");
            }
            if (!whiteLabel.getDomain().equals(createWhiteLabelDto.getDomain()) && whiteLabelService.existsByDomain(createWhiteLabelDto.getDomain())) {
                throw new ProgramException("域名已存在");
            }
            if (!createWhiteLabelDto.getAdminDomain().equals(whiteLabel.getAdminDomain()) && whiteLabelService.existsByAdminDomain(createWhiteLabelDto.getAdminDomain())) {
                throw new ProgramException("后台域名已存在");
            }
        } else {
            whiteLabel = new WhiteLabel();
            if (whiteLabelService.existsByDomain(createWhiteLabelDto.getDomain())) {
                throw new ProgramException("域名已存在");
            }
        }
        whiteLabel.setDomain(createWhiteLabelDto.getDomain());
        whiteLabel.setAdminDomain(createWhiteLabelDto.getAdminDomain());
        whiteLabel.setName(createWhiteLabelDto.getName());
        whiteLabel.setLogo(createWhiteLabelDto.getLogo());
        whiteLabel.setHomeLogo(createWhiteLabelDto.getHomeLogo());
        whiteLabel.setLoginLeftImage(createWhiteLabelDto.getLoginLeftImage());
        whiteLabel.setRemark(createWhiteLabelDto.getRemark());
        whiteLabel.setStatus(2); // 默认状态为审核
        whiteLabel.setBossUserId(BossUserUtil.getId());
        // 保存白标信息
        whiteLabelService.saveOrUpdate(whiteLabel);
    }


    @RestPack
    @PostMapping("audit")
    @SaCheckLogin
    @RepeatSubmit
    @SaCheckPermission("admin:brandable:audit")
    @SaCheckSafe("BRANDABLE_AUDIT")
    public Boolean audit(@RequestBody @Validated AuditWhiteLabelDto auditWhiteLabelDto) {
        // 创建白标信息
        return whiteLabelService.audit(auditWhiteLabelDto.getId(), auditWhiteLabelDto.getStatus(), auditWhiteLabelDto.getRemark());

    }


    @RestPack
    @PostMapping("updateStatus")
    @SaCheckLogin
    @RepeatSubmit
    @SaCheckPermission("admin:brandable:status:edit")
    @SaCheckSafe("BRANDABLE_STATUS_EDIT")
    public Boolean updateStatus(@RequestBody @Validated UpdateWhiteLabelDto updateWhiteLabelDto) {
        // 创建白标信息
        return whiteLabelService.updateStatus(updateWhiteLabelDto.getId(), updateWhiteLabelDto.getStatus() ? 0 : 3);

    }


    @RestPack
    @GetMapping("getCopyDomain")
    @SaCheckLogin
    @RepeatSubmit
    public String getCopyDomain(
            @RequestHeader String source
    ) {
        if ("boss.allwincard.com".equals(source)) {
            return "www.allwincard.com";
        }
        WhiteLabel whiteLabel = whiteLabelService.getByAdminDomain(source);
        return whiteLabel != null ? whiteLabel.getDomain() : "";
    }
}
